package q4_lock_test;

import lombok.Getter;

import java.util.concurrent.CountDownLatch;

enum CountryEnum {
    ONE(1, "齐"), TWO(2, "楚"), THREE(3, "燕"), FOUR(4, "赵"), FIVE(5, "魏"), SIX(6, "韩");

    @Getter
    private Integer code;
    @Getter
    private String country;

    CountryEnum(Integer code, String country) {
        this.code = code;
        this.country = country;
    }

    public static CountryEnum foreach(int index){
        CountryEnum[] values = CountryEnum.values();
        for (CountryEnum countryEnum : values) {
            if(countryEnum.code == index){
                return countryEnum;
            }
        }
        return null;
    }
}

/*
让一些线程阻塞直到另一些线程完成一系列操作后才被唤醒
CountDownLatch主要有两个方法，当一个或多个线程调用await方法时，调用线程会被阻塞。
其它线程调用countDown方法会将计数器减1（调用countDown方法的线程不会阻塞），
当计数器的值变为零时，因调用await方法被阻塞的线程会被唤醒，继续执行。

倒计时 万箭齐发
*/
public class CountDownLatchDemo {
    public static void main(String[] args) throws Exception {

        //closeDoor();

        CountDownLatch countDownLatch = new CountDownLatch(6);

        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "\t 国，被灭");
                countDownLatch.countDown();
            }, CountryEnum.foreach(i).getCountry()).start();
        }

        countDownLatch.await();
        System.out.println(Thread.currentThread().getName() + "\t*********秦帝国，一统华夏");

    }

    public static void closeDoor() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(6);

        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "\t上完自习，离开教室");
                countDownLatch.countDown();
            }, "" + i).start();
        }

        countDownLatch.await();
        System.out.println(Thread.currentThread().getName() + "\t*********班长最后关门走人");
    }
}
